package gweb

import (
	"fmt"
	"github.com/beego/beego/v2/client/cache"
	_ "github.com/beego/beego/v2/client/cache/redis"
	"github.com/beego/beego/v2/core/logs"
)

var (
	caches           map[string]cache.Cache
	defaultCacheName string
)

func initCache() {
	if viperConfig.Cache.Enable == false {
		return
	}
	if viperConfig.Cache.List == nil {
		logs.Error("cache config is not found")
		return
	}
	if len(viperConfig.Cache.List) == 0 {
		logs.Error("log config is empty")
		return
	}
	for _, v := range viperConfig.Cache.List {
		if v.Enable {
			if e := addCache(v); e != nil {
				logs.Error(e.Error())
			}
		}
	}
}

// addCache 注册缓存实例
func addCache(cacheConfig CacheConfig) error {
	_cache, err := cache.NewCache(cacheConfig.Type, cacheConfig.Option)
	if err != nil {
		return fmt.Errorf("cache type:%s init err:%s", cacheConfig.Type, err.Error())
	}
	if caches == nil {
		caches = make(map[string]cache.Cache)
	}
	if _, ok := caches[cacheConfig.Name]; ok {
		return fmt.Errorf("cache name:%s is repetition", cacheConfig.Name)
	}
	caches[cacheConfig.Name] = _cache
	if cacheConfig.Default {
		defaultCacheName = cacheConfig.Name
	}
	return nil
}

// GetCache 获取缓存实例
func GetCache(name ...string) (cache.Cache, error) {
	var cacheName string
	if len(name) == 0 {
		if defaultCacheName == "" {
			return nil, fmt.Errorf("default cache is not exist")
		}
		cacheName = defaultCacheName
	} else {
		cacheName = name[0]
	}
	if v, ok := caches[cacheName]; ok {
		return v, nil
	} else {
		return nil, fmt.Errorf("cache name:%s is not exist", cacheName)
	}
}
